import 'dart:io';

import 'package:dio/dio.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/event/RouteEvent.dart';

class HttpUtil{
  Future<dynamic> get(String url) async{
    // 先获取用户的token
    String token = Config().getToken() ;
    if(token == null){
      eventBus.fire(RouteEvent("login"));
    }
    BaseOptions header = BaseOptions(headers: {"token": token} , connectTimeout: 1500 , receiveTimeout: 800);
    Dio dio = new Dio(header) ;
    try {
      Response response = await dio.get(url).catchError((res){
        if(res.response.statusCode == 401){
          eventBus.fire(RouteEvent("login"));
        }
      }) ;
      if(response.headers.value("token")[0] != null){
        Config().setToken(response.headers["token"][0]) ;
      }
      return response.data ;
    } catch (e) {
      return throw e ;
    }
  }

  Future<dynamic> post(String url , dynamic params) async{
    // 先获取用户的token
    String token = Config().getToken() ;
    if(token == null){
      eventBus.fire(RouteEvent("login"));
    }
    BaseOptions header = BaseOptions(headers: {"token": token} , connectTimeout: 1500 , receiveTimeout: 800);
    Dio dio = new Dio(header) ;
    try {
      Response response = await dio.post(url , queryParameters: params).catchError((res){
        if(res.response.statusCode == 401){
          eventBus.fire(RouteEvent("login"));
        }
      }) ;
      if(response.headers.value("token")[0] != null){
        Config().setToken(response.headers["token"][0]) ;
      }
      return response.data ;
    } catch (e) {
      return null ;
    }
  }

  Future<dynamic> upload(String url , File file , {onProcess}) async{
    // 先获取用户的token 
    String token = Config().getToken() ;
    if(token == null){
      eventBus.fire(RouteEvent("login"));
    }
    Options header = Options(headers: {"token": token});
    Dio dio = new Dio() ;

    var name = file.path.substring(file.path.lastIndexOf("/") + 1, file.path.length);
    var postData = FormData.fromMap({
      "file": await MultipartFile.fromFile(
          file.path, filename: name)
    });

    try {
      var responce = await Dio().post(url,data:postData,onSendProgress: (int sent, int total) {
      //  print("$sent $total"); //send是上传的大小 total是总文件大小
        if(onProcess != null){
          onProcess(sent / total) ;
        }
      },options: header).catchError((res){
        if(res.response.statusCode == 401){
          eventBus.fire(RouteEvent("login"));
        }
      }) ;
      print(responce) ;
      if(responce.headers.value("token")[0] != null){
        Config().setToken(responce.headers["token"][0]) ;
      }
      return responce.data ;
    } catch (e) {
      print(e) ;
      return null ;
    }
  }
}